/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/maximum-subarray-difference
   @Language: C++
   @Datetime: 16-02-09 08:17
   */

class Solution {
	int maxDiffCore(vector<int> &nums)
	{
		int N=nums.size(), i, sum, mx;
		vector<int> leftmax(N,0),rightmin(N,0);
		for(sum=i=0, mx=INT_MIN; i<N; ++i){
			sum += nums[i];
			mx = max(mx,sum);
			if(sum<0) sum=0;
			leftmax[i] = mx;
		}
		for(sum=0, i=N, mx=INT_MAX; i--;){
			sum += nums[i];
			mx = min(mx,sum);
			if(sum>0) sum=0;
			rightmin[i] = mx;
		}
		for(i=1, mx=0; i<N; i++)
			mx = max(mx,abs(leftmax[i-1]-rightmin[i]));
		return mx;
	}
	
public:
	/**
	 * @param nums: A list of integers
	 * @return: An integer indicate the value of maximum difference between two
	 *          Subarrays
	 * Tip : get max_lr and min_rl, cal max-diff
	 *       get max_rl  and min_lr, cal max-diff
	 */
	int maxDiffSubArrays(vector<int> nums) {
		// write your code here
		if (nums.size()<2) return 0;
		int x1 = maxDiffCore(nums);
		reverse(nums.begin(),nums.end());
		int x2 = maxDiffCore(nums);
		return max(x1,x2);
	}
};
